<template>
  <transition name="tz-overlay-fade">
    <view
      v-show="overlay && modelValue"
      style="animationduration: 0.25s;"
      class="tz-overlay"
      :catch-move="true"
      @tap.stop="handleOverClick"
    />
  </transition>
  <transition :name="'tz-popup-fade-' + position">
    <view
      v-show="modelValue"
      :catch-move="true"
      :style="['animationduration: 0.25s;', 'height:' + height]"
      :class="['tz-popup', 'tz-popup--' + position]"
    >
      <slot />
    </view>
  </transition>
</template>
<script>
export default {
  name: "TzPopup",
  inheritAttrs: false,
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
    overlay: {
      type: Boolean,
      default: true,
    },
    position: {
      default: "top",
      validator(value) {
        // 这个值必须匹配下列字符串中的一个
        return ["top", "bottom", "right", "left"].includes(value);
      },
    },
    duration: {
      type: Number,
      default: 3000,
    },
    height: {
      type: String,
      default: "30%",
    },
    offset: {
      type: [String, Number],
      default: 0,
    },
  },
  emits: ["close", "open", "update:modelValue"],
  setup(props, { emit }) {
    const close = () => {
      emit("close");
      emit("update:modelValue", false);
    };

    const open = () => {
      emit("open");
      emit("update:modelValue", true);
    };

    //点击蒙层
    const handleOverClick = () => {
      close();
    };

    return { open, close, handleOverClick };
  },
};
</script>

<style lang="scss">
.tz-overlay {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.4);
  transition: opacity 0.25s;
  z-index: 1999;
}
.tz-popup {
  position: fixed;
  max-height: 100%;
  overflow-y: auto;
  background-color: #fff;
  z-index: 2000;
  -webkit-overflow-scrolling: touch;
  transition: transform 0.25s;

  &--top {
    top: 0;
    left: 0;
    width: 100%;
  }

  &--bottom {
    bottom: 0;
    left: 0;
    width: 100%;
  }
}

.tz-overlay-fade {
  &-enter-from,
  &-leave-to {
    opacity: 0;
  }

  &-enter-active,
  &-leave-active {
    transition: opacity 0.25s;
  }

  &-enter-to,
  &-leave-from {
    opacity: 1;
  }
}

.tz-popup-fade-top {
  &-enter-from,
  &-leave-to {
    transform: translate3d(0, -100%, 0);
  }
}

.tz-popup-fade-bottom {
  &-enter-from,
  &-leave-to {
    transform: translate3d(0, 100%, 0);
  }
}

.tz-popup-fade-top,
.tz-popup-fade-bottom {
  &-enter-active,
  &-leave-active {
    transition-property: transform;
    transition-timing-function: ease;
  }

  &-enter-to,
  &-leave-from {
    transform: translateZ(0);
  }
}
</style>
